﻿using HW.Application.Share.Events;
using HW.Application.Share.Prism;
using HW.Core.Ioc;
using HW.Database.SQLServer;
using HW.Database.SQLServer.Repository;
using HW.Logger;
using HWcommunication;
using Prism.Commands;
using Prism.Events;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace HW.Application.PlcBusiness.Services
{
    public class PlcService
    {
        public bool isVisibil = false;

        private IEventAggregator _eventAggregator;

        protected CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

        public DelegateCommand IsVisibilCommand { get; }

        private HWcommunicate hWcommunication = new HWcommunicate ();
        private IRotorInformationRepository RotorInformationRepository { get; }

        public PlcService( )
        {
            RotorInformationRepository = new RotorInformationRepository();
            PrismProvider.Dispatcher.Invoke(() =>
            {
                PrismProvider.EventAggregator.GetEvent<HideWindowEvent>().Subscribe(() => isVisibil = false, ThreadOption.UIThread);
            });
        }

        

        public void Start()
        {
            try
            {

                //string Con_Status1 = hWcommunication.Con_To_PLC("192.168.3.249", 8501, "732576");


                string Con_Status1 = hWcommunication.Con_To_PLC("192.168.0.10", 8501, "732576");
                if (Con_Status1 == "ok") 
                {
                    Logs.LogInfo("连接PLC\"192.168.0.10\"成功！！！");
                    Thread Son1_Thread = new Thread(new ThreadStart(delegate
                    {
                        while (!cancellationTokenSource.IsCancellationRequested)
                        {
                            this.ReadData();
                            Thread.Sleep(100);
                        }
                    }));

                    Son1_Thread.Start();

                }
            }
            catch (Exception ex)
            {
                
                Logs.LogError(ex);
                cancellationTokenSource.Cancel();
                Console.WriteLine("updateAll >-- " + ex);
                PrismProvider.Dispatcher.Invoke(() => { MessageBox.Show("连接PLC失败重启设备"); });
            }
        }
        int i = 0;
        private void ReadData()
        {
            //测量完成
            string ReadHistoricalDataSave = hWcommunication.Read_Bit("MR40406");
            //打开弹框
            string ReadDataPopup = hWcommunication.Read_Bit("MR201");
                //现场测量完成位
            if (ReadHistoricalDataSave == "1")
            {
                
                hWcommunication.RES_Addr("MR40406");
                SaveData();

            }

            if (!isVisibil && ReadDataPopup == "1")
            {
                
                OpenMainWindow();
                isVisibil = true;
                
                
                
                hWcommunication.RES_Addr("MR201");
            }
            else
            {
                if (ReadDataPopup == "1")
                {
                    hWcommunication.RES_Addr("MR201");
                }
            }


        }

        private void SaveData()
        {
            RotorInformation rotorInformation = new RotorInformation();

            

            rotorInformation.CreateDateTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

            rotorInformation.ProductNumber = hWcommunication.Read_String("EM16340", 10);


            rotorInformation.NumberOfJobs = hWcommunication.Read_String("EM142", 4);
   

            
            rotorInformation.AllowableError1 = (decimal)hWcommunication.Read_Float("EM290");

            rotorInformation.AllowableError2 = (decimal)hWcommunication.Read_Float("EM292");

            rotorInformation.AllowableError3 = (decimal)hWcommunication.Read_Float("EM294");

            rotorInformation.AllowableError4 = (decimal)hWcommunication.Read_Float("EM296");

            rotorInformation.UnbalanceAmount1InGrams = (decimal)hWcommunication.Read_Float("EM6080");

            rotorInformation.UnbalanceAmount1InGramsUnit = hWcommunication.Read_String("EM5162", 1);

            rotorInformation.AngleFace1 = (decimal)hWcommunication.Read_Float("EM3060");

            rotorInformation.UnbalanceAmount2InGrams = (decimal)hWcommunication.Read_Float("EM6082");

            rotorInformation.UnbalanceAmount2InGramsUnit = hWcommunication.Read_String("EM5178", 1);

            rotorInformation.AngleFace2 = (decimal)hWcommunication.Read_Float("EM3064");

            rotorInformation.UnbalanceAmount3InGrams = (decimal)hWcommunication.Read_Float("EM6084");

            rotorInformation.UnbalanceAmount3InGramsUnit = hWcommunication.Read_String("EM5182", 1);

            rotorInformation.AngleFace3 = (decimal)hWcommunication.Read_Float("EM3068");

            rotorInformation.UnbalanceAmount4InGrams = (decimal)hWcommunication.Read_Float("EM6086");

            rotorInformation.UnbalanceAmount4InGramsUnit = hWcommunication.Read_String("EM5166", 1);

            rotorInformation.AngleFace4 = (decimal)hWcommunication.Read_Float("EM3072");

            bool result = RotorInformationRepository.Insert(rotorInformation);
#if DEBUG

            Console.WriteLine(result);
            Console.WriteLine($"AllowableError: {rotorInformation.AllowableError1} + {rotorInformation.AllowableError2} + {rotorInformation.AllowableError3} + {rotorInformation.AllowableError4}");
            Console.WriteLine($"CreateDateTime: {rotorInformation.CreateDateTime}");
            Console.WriteLine($"ProductNumber: {rotorInformation.ProductNumber}");
            Console.WriteLine($"NumberOfJobs: {rotorInformation.NumberOfJobs}");
#endif
        }

        private void OpenMainWindow()
        {
            PrismProvider.Dispatcher.Invoke(() =>
                {
                    //加载主界面
                    PrismProvider.EventAggregator.GetEvent<ShowWindowEvent>().Publish();
                    
                });
        }
#if DEBUG
        private void UpdateHistorySheet()
        {
            PrismProvider.Dispatcher.Invoke(() =>
            {
                //加载主界面
                PrismProvider.EventAggregator.GetEvent<UpdateHistorySheetEvent>().Publish();

            });
        }
#endif

    }
}
